#!/bin/sh

# Copyright (C) 2017 VMware, Inc.  All rights reserved. -- VMware Confidential

sourceCafenv() {
	local configDir=$1
	local cafenvAppconfig="$configDir/cafenv-appconfig"

	if [ ! -f "$cafenvAppconfig" ]; then
		echo "*** cafenv-appconfig file not found - $cafenvAppconfig"
		exit 1
	fi

	local tmpCafenv="/tmp/_cafenv-appconfig_"
	cat "$cafenvAppconfig" | sed 's/^\[/#[/g' | sed 's/^\([a-z].*=\)/export CAF_\U\1/g' > "$tmpCafenv"
	sed -i 's/[ ]*=[ ]*/=/g' "$tmpCafenv"
	. "$tmpCafenv"
	if [ "$CAF_INSTALL_MODE" = "standalone" ]; then
                export LD_LIBRARY_PATH=$CAF_LIB_DIR
	else
                export LD_LIBRARY_PATH="$CAF_TOOLS_LIB_DIR/libvgauth.so/:$CAF_TOOLS_LIB_DIR/libcrypto.so.1.0.2/:$CAF_TOOLS_LIB_DIR/libssl.so.1.0.2/:$CAF_TOOLS_LIB_DIR/libz.so.1/:$CAF_TOOLS_LIB_DIR/libffi.so.6/:$CAF_TOOLS_LIB_DIR/libiconv.so.2/:$CAF_TOOLS_LIB_DIR/libpcre.so.1/:$CAF_TOOLS_LIB_DIR/libglib-2.0.so.0/:$CAF_TOOLS_LIB_DIR/libgcc_s.so.1/:$CAF_TOOLS_LIB_DIR/libgthread-2.0.so.0/:$CAF_TOOLS_LIB_DIR/libstdc++.so.6/:$CAF_LIB_DIR"
	fi
        export VMWARE_USE_SYSTEM_LIBS=1
}

getCurrentDir() {
	return $(dirname $(readlink -f $0))
}

startCafProcess() {
	local startType="$1"
	local startDir="$2"
	local processDir="$3"
	local processName="$4"

	local processPath="$processDir/$processName"
	verifyProcessNotRunning "$processPath"
	setUtf8Locale

	mkdir -p "$startDir"
	cd "$startDir"

	case "$startType" in
		"daemon")
			$processPath
		;;
		"foreground")
			$processPath -n
		;;
		"valgrindMemChecks")
			G_SLICE=always-malloc G_DEBUG=gc-friendly valgrind -v --tool=memcheck --leak-check=full --num-callers=40 --track-origins=yes --leak-resolution=med --track-fds=yes --log-file=${processPath}-valgrind-memchecks.log $processPath -n
		;;
		"valgrindProfiling")
			valgrind --tool=callgrind --log-file=${processPath}-valgrind-profiling.log $processPath -n
		;;
		"valgrindThreading")
			valgrind --tool=helgrind --track-lockorders=no --log-file=${processPath}-valgrind-threading.log $processPath -n
		;;
		*)
			echo "Unknown startType - $startType"; exit 1
		;;
	esac
}

startVgAuthProcess() {
	local startType="$1"
	local startDir="$2"
	local processDir="$3"
	local processName="$4"

	local processPath="$processDir/$processName"
	verifyProcessNotRunning "$processPath"
	setUtf8Locale

	mkdir -p "$startDir"
	cd "$startDir"

	# Run the processes using -s rather than -d if you want the logging to go the file instead of the console
	case "$startType" in
		"daemon")
			# This is supposed to start the service as a daemon, but it's failing... perhaps because the service
			# hasn't been registered - see above.
			#./$processName -b

			# -s tells it to log to a file, -d to the console
			nohup $processPath -s > ${processPath}.out 2>&1 &
		;;
		"foreground")
			$processPath -d
		;;
		"valgrindMemChecks")
			G_SLICE=always-malloc G_DEBUG=gc-friendly  valgrind -v --tool=memcheck --leak-check=full --show-leak-kinds=all --num-callers=40 --log-file=${processPath}-valgrind.log $processPath -d
		;;
		"valgrindProfiling")
			valgrind --tool=callgrind $processPath -d
		;;
		*)
			echo "Unknown startType - $startType"; exit 1
		;;
	esac
}

#Set the locale to something UTF8
setUtf8Locale() {
	locale_list=`locale | egrep -vi '.utf8|.utf-8|=$|LANGUAGE'`
        if [ $? -eq 0 ]; then
		echo "The locale is currently set to $LANG, looking for UTF-8"
                default_locale=$LANG
                available_utf8_locales=`locale -a | egrep -i '.utf8|.utf-8' | egrep -vi '^c.utf'`
		if [ ! -z "$available_utf8_locales" ]; then
			for loc in $available_utf8_locales; do
                                best_locale=$loc
                                is_en_US_locale=`echo $loc | egrep -i 'en_US'`
                                if [ ! -z $is_en_US_locale ]; then
                                        echo "$loc is the best UTF-8 locale required"
                                        break
                                fi
                        done
			echo "Using the available UTF-8 locale: $best_locale"
                else
                        echo "No UTF-8 locale found, using the default locale $default_locale"
                        best_locale=$default_locale
                fi

                export LANG=$best_locale
                export LANGUAGE=$best_locale
                export LC_ALL=$best_locale

                echo "The locale is now successfully set to : $LANG"

        else
                echo "The locale is already set to UTF-8 : $LANG"
        fi
}

verifyProcessNotRunning() {
	local processPath=$1

	pid=$(ps aux | egrep "${processPath}" | egrep -v "color=auto|grep" | awk '{print $2}')
	if [ ! -z "$pid" ]; then
		echo "$processPath is already running - $pid"; exit 0
	fi
}

stopProcess() {
	local processDir=$1
	local processName=$2

	local processPath="$processDir/$processName"

	pid=$(ps aux | egrep "${processPath}" | egrep -v "color=auto|grep" | awk '{print $2}')
	if [ -z "$pid" ]; then
		echo "$processPath not found"
	else
		echo "Stopping $processPath - $pid"
		counter=0
		while [ ! -z "$pid" ]; do
			if [ $counter -lt 20 ]; then
				kill $pid
			else
				echo "Killing $processPath with prejudice- $pid"
				kill -9 $pid
			fi
			counter=`expr $counter + 1`;
			#echo "counter=$counter"
			sleep 1
			pid=$(ps aux | egrep "${processPath}" | egrep -v "color=auto|grep" | awk '{print $2}')
		done
	fi
}

enableCoreFiles() {
	ulimit -c unlimited
}
